package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.adapter.ExpertFirstAdapter;
import com.digitalchina.lxnsy.adapter.ExpertSecondAdapter;
import com.digitalchina.lxnsy.adapter.ExpertThreeAdapter;
import com.digitalchina.lxnsy.api.BusinessExpert;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.ExpertClassificationVO;
import com.digitalchina.lxnsy.entity.ExpertNewVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.ExpertListHolder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：专家咨询列表
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/3/25 18:00
 * 修改备注：这个列表为项目正在使用的列表  2017年4月6日 15:09:46
 * ================================================
 */

public class ExpertsListActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {


    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.agricultural_experts_iv_information)
    TextView agriculturalExpertsTvInformation;
    @Bind(R.id.listViewFirst)
    ListView listViewFirst;
    @Bind(R.id.listViewSecond)
    ListView listViewSecond;
    @Bind(R.id.data_mall_drawer_layout)
    DrawerLayout dataMallDrawerLayout;
    @Bind(R.id.listViewThree)
    ListView listViewThree;

    private RecyclerArrayAdapter adapter;
    private int page = 1;
    private int limit = 10;

    private List<ExpertNewVO> expertVOList = new ArrayList<>();

    private ExpertFirstAdapter firstAdapter;
    private ExpertSecondAdapter secondAdapter;
    private ExpertThreeAdapter threeAdapter;

    private List<ExpertClassificationVO.ResearchFieldTwoStagesBean> emptyList = new ArrayList<>(); // 二级菜单 空list
    private List<ExpertClassificationVO.ResearchFieldTwoStagesBean.ResearchFieldThreeStageVosBean> emptyList3 = new ArrayList<>(); // 三级菜单 空list

    // 1级分类
    private List<ExpertClassificationVO> expertClassificationVOList = new ArrayList<>();
    // 2级分类
    private List<ExpertClassificationVO.ResearchFieldTwoStagesBean> secondList = new ArrayList<>();
    // 3级分类
    private List<ExpertClassificationVO.ResearchFieldTwoStagesBean.ResearchFieldThreeStageVosBean> threeList = new ArrayList<>();
    // 3级领域
    private List<List<ExpertClassificationVO.ResearchFieldTwoStagesBean.ResearchDirectionVosBean>> areaList = new ArrayList<>();

    private OptionsPickerView pvOptions;

    private boolean tag = false;

    //    private String minTypeName = "";
    private String minTypeCode = "";
    private TextView textView;

    //    private boolean isTypeData = false;
    private int p1; // 第1个list下标
    private int p2; // 第2个list下标

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_expert_list);
    }


    @Override
    public void initMember() {
        setTitle("农业专家列表");
//        setRightImage(R.drawable.icon_menu_white);
        setRightText("分类");
        initRecyclerView();
        // 获取所有类型
        BusinessExpert.expertTypeChat(this,"2",  mHandler);


        secondAdapter = new ExpertSecondAdapter(ExpertsListActivity.this, emptyList);
        listViewSecond.setAdapter(secondAdapter);
        threeAdapter = new ExpertThreeAdapter(ExpertsListActivity.this, emptyList3);
        listViewThree.setAdapter(threeAdapter);
    }

    private void initRecyclerView() {

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.addItemDecoration(Utils.setSpaceDecoration(this, false, true, false));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new ExpertListHolder(parent);
            }
        });

        onRefresh();
    }


    @Override
    public void addListener() {
        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {

                Map<String, Object> map = new HashMap<>();
//                map.put("expertTypeVOList", expertTypeVOList);
//                map.put("listList", listList);
                map.put("ExpertVO", adapter.getAllData().get(position));

//                GotoUtil.gotoActivity(ExpertsListActivity.this, AgriculturalExpertsDetailsActivity.class, "map", map);
                GotoUtil.gotoActivity(ExpertsListActivity.this, AgriculturalExpertsDetailsActivity.class, "map", map);
            }
        });

        listViewFirst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                if (position == 0) {
//                    isTypeData = false;
                    minTypeCode = "";
                    dataMallDrawerLayout.closeDrawer(GravityCompat.START);
                    textView.setBackgroundResource(R.drawable.shape_real_time_type);
                    secondAdapter.setDatas(emptyList);
                    onRefresh();
                } else {
                    p1 = position - listViewFirst.getHeaderViewsCount();
                    textView.setBackgroundResource(R.drawable.shape_data_type_null);
                    updateListView(position - listViewFirst.getHeaderViewsCount());
                }
                threeAdapter.setDatas(emptyList3);
                threeAdapter.notifyDataSetChanged();
                firstAdapter.setSelectPosition(position - listViewFirst.getHeaderViewsCount());
                firstAdapter.notifyDataSetChanged();
            }
        });


        listViewSecond.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                p2 = position;
                updateListView2(position);
                secondAdapter.setSelectPosition(position);
                secondAdapter.notifyDataSetChanged();
            }
        });

        listViewThree.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                updateListView3(position, true);

                threeAdapter.setSelectPosition(position);
                threeAdapter.notifyDataSetChanged();
            }
        });


        agriculturalExpertsTvInformation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (!Utils.isLogin(ExpertsListActivity.this)) {
                    startActivityForResult(new Intent(ExpertsListActivity.this, LoginActivity.class), 1);
                } else {
                    GotoUtil.gotoActivity(ExpertsListActivity.this, ConsultIssueV2Activity.class, "multi", "");
                }


            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_GET_CHAT_EXPERTS_SUCCESS: // 专家列表
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_CHAT_EXPERTS_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                    case MSG.MSG_EXPERT_TYPE_CHAT_SUCCESS: // 专家分类 <侧边栏>
                        setLeftView(msg.obj.toString());
//                        initOptionPicker();
                        break;
                    case MSG.MSG_EXPERT_TYPE_CHAT_FIELD:
                        break;
                }
            }
        };
    }

    /**
     * 设置左侧类型
     */
    private void setLeftView(String json) {
        expertClassificationVOList = FastJsonUtil.getListBean(json, "typeList", ExpertClassificationVO.class);

        if (expertClassificationVOList == null || expertClassificationVOList.size() == 0)
            return;


        firstAdapter = new ExpertFirstAdapter(ExpertsListActivity.this, expertClassificationVOList);

        View view = LayoutInflater.from(ExpertsListActivity.this).inflate(R.layout.item_mall_type, null);
        textView = (TextView) view.findViewById(R.id.item_tv_type);
        textView.setBackgroundResource(R.drawable.shape_real_time_type);
        textView.setText("全部分类");
        listViewFirst.addHeaderView(view);

        listViewFirst.setAdapter(firstAdapter);
        firstAdapter.setSelectPosition(-1);
        firstAdapter.notifyDataSetChanged();

    }


    private void updateListView(int position) {

        secondList.clear();
        //更新第二ListView
        for (int i = 0; i < expertClassificationVOList.get(position).getResearchFieldTwoStages().size(); i++) {
            secondList.add(expertClassificationVOList.get(position).getResearchFieldTwoStages().get(i));
        }

        secondAdapter.setDatas(secondList);
        secondAdapter.setSelectPosition(-1);
        secondAdapter.notifyDataSetChanged();
    }

    private void updateListView2(int position) {

        threeList.clear();
        //更新第三ListView
        for (int i = 0; i < expertClassificationVOList.get(p1).getResearchFieldTwoStages().get(position).getResearchFieldThreeStageVos().size(); i++) {
            threeList.add(expertClassificationVOList.get(p1).getResearchFieldTwoStages().get(position).getResearchFieldThreeStageVos().get(i));
        }
        threeAdapter.setDatas(threeList);
        threeAdapter.setSelectPosition(-1);
        threeAdapter.notifyDataSetChanged();
    }

    private void updateListView3(int position, boolean b) {


        if (b) {
            dataMallDrawerLayout.closeDrawer(GravityCompat.START);
            minTypeCode = threeAdapter.getItem(position).getCode();
//            isTypeData = true;
            onRefresh();
        }
    }

    @Override
    public void callBack(Object object) {
//        if (isTypeData)
//            expertVOList = FastJsonUtil.getListBean(object.toString(), "body", "expertList", ExpertNewVO.class);
//        else
        expertVOList = FastJsonUtil.getListBean(object.toString(), "body", "expertList", ExpertNewVO.class);


        if (page == 1) { // 刷新
            adapter.clear();
        }

        if (expertVOList != null) {
            if (expertVOList.size() < limit) {
                adapter.stopMore();
            }
        }
        adapter.addAll(expertVOList);
    }

    @Override
    public void rightOnClick() {
        if (dataMallDrawerLayout.isDrawerVisible(GravityCompat.START))
            dataMallDrawerLayout.closeDrawer(GravityCompat.START);
        else {
            dataMallDrawerLayout.openDrawer(GravityCompat.START);
            if (expertClassificationVOList == null && expertClassificationVOList.size() == 0)
                // 获取所有类型
                BusinessExpert.expertTypeChat(ExpertsListActivity.this,"2", mHandler);
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }


    @Override
    public void onRefresh() {
        page = 1;
        BusinessExpert.getChatExperts(ExpertsListActivity.this, String.valueOf(page), String.valueOf(limit), minTypeCode, "", mHandler);
    }

    @Override
    public void onLoadMore() {
        page++;
        BusinessExpert.getChatExperts(ExpertsListActivity.this, String.valueOf(page), String.valueOf(limit), minTypeCode, "", mHandler);
    }

    /**
     * 条件选择器初始化
     */
    private void initOptionPicker() {

//        if (expertTypeVOList == null || expertTypeVOList.size() == 0)
//            return;
//
//        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
//            @Override
//            public void onOptionsSelect(int options1, int option2, int options3, View v) {
//                //返回的分别是三个级别的选中位置
//                if (null == expertTypeVOList || expertTypeVOList.size() <= 0)
//                    return;
//                QuestionTypeVO.ResearchFieldTwoStagesBean typeVO = expertTypeVOList.get(options1);
//                QuestionTypeVO.ResearchFieldTwoStagesBean.ResearchFieldThreeStageVosBean listBean = listList.get(options1).get(option2);
//                Map<String, Object> map = new HashMap<>();
//                map.put("typeVO", typeVO);
//                map.put("listBean", listBean);
//                GotoUtil.gotoActivity(ExpertsListActivity.this, ConsultIssueV2Activity.class, "map", map);
//            }
//        })
//                .setSubmitText("下一步")
//                .setCancelText("取消")
//                .setTitleText("咨询分类")
//                .setSubCalSize(16)//确定取消按钮大小
//                .setLineSpacingMultiplier(1.7f) //设置两横线之间的间隔倍数（范围：1.2 - 2.0倍 文字高度）
//                .setDividerColor(getResources().getColor(R.color.app_color))//设置分割线的颜色
//                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
//                .setContentTextSize(18)//设置滚轮文字大小
//                .setSelectOptions(0, 0)  //设置默认选中项
//                .build();
//
//        pvOptions.setPicker(expertTypeVOList, listList);
//
//        if (tag)
//            pvOptions.show();

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (dataMallDrawerLayout.isDrawerVisible(GravityCompat.START)) {
                dataMallDrawerLayout.closeDrawer(GravityCompat.START);
                return true;
            }
            if (pvOptions != null && pvOptions.isShowing()) {
                pvOptions.dismiss();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onResume() {
        super.onResume();
        tag = false; // 默认将tag置为false  避免自动弹出选择器
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
